using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using Hotran.SaveSystem;

public class Cable : MonoBehaviour, ISavable
{
    private struct SaveData
    {
        public Cable Parent;
        public bool IsLit;
    }

    public event System.Action Lit;

    public bool IsSource => _isSource;

    public Cable Parent { get; private set; } = null;

    public bool IsLit { get; private set; } = false;

    [SerializeField]
    private bool _isSource = false;

    [SerializeField]
    private SpriteShapeRenderer _electricRenderer;
    private Material[] _electricMaterials;


    private void Awake()
    {
        _electricMaterials = _electricRenderer.materials;

        SetParent(null);
    }

    public bool IsConnectedToSource(out Cable sourceCable)
    {
        sourceCable = null;
        if (IsSource)
        {
            sourceCable = this;
            return true;
        }
        if (Parent == null)
            return false;

        int count = 0;
        Cable ptr = Parent;
        while (ptr != null)
        {
            if (ptr.IsSource)
            {
                sourceCable = ptr;
                return true;
            }
            ptr = ptr.Parent;

            count++;
            if (count > 100)
                throw new System.Exception("Too many loops");
        }
        return false;
    }

    public void SetParent(Cable parent)
    {
        Parent = parent;

        if (IsConnectedToSource(out _))
        {
            SetLit();
        }
        else
        {
            ResetLit();
        }
    }

    public object Save()
    {
        return new SaveData()
        {
            Parent = Parent,
            IsLit = IsLit
        };
    }

    public void Load(object data)
    {
        SaveData saveData = (SaveData)data;
        Parent = saveData.Parent;
        if (saveData.IsLit)
            SetLit();
        else
            ResetLit();
    }

    private void SetLit()
    {
        IsLit = true;
        //Debug.Log(_electricMaterials[1].GetFloat("_Float"));
        _electricMaterials[1].SetFloat("_Float", 1f);

        Lit?.Invoke();
    }

    private void ResetLit()
    {
        IsLit = false;
        _electricMaterials[1].SetFloat("_Float", 0f);
    }
}
